import React, { useState, useMemo, useRef, useEffect } from "react";
import { Slate, Editable, ReactEditor, withReact, useSlate } from "slate-react";
import { Editor, Transforms, Text, createEditor, Node } from "slate";
import { css } from "emotion";
import { withHistory } from "slate-history";

import { Button, Icon, Menu, Portal } from "./components";
import { Range } from "slate";
import { OperateTable } from "./Table/TableEvent";

const OperatorButton = ({ type }) => {
  const editor = useSlate();
  return (
    <Button
      reversed
      onMouseDown={(event) => {
        event.preventDefault();
        MouseDownHandler(editor, type);
      }}
    >
      {type}
    </Button>
  );
};

const MouseDownHandler = (editor, type) => {
  OperateTable(editor, type);
};

export default () => {
  const ref = useRef /*<HTMLDivElement | null>*/();
  const editor = useSlate();

  useEffect(() => {
    const el = ref.current;
    const { selection } = editor;

    if (!el) {
      return;
    }

    if (
      !selection ||
      !ReactEditor.isFocused(editor) ||
      Range.isCollapsed(selection) ||
      Editor.string(editor, selection) === ""
    ) {
      el.removeAttribute("style");
      return;
    }

    if (editor) {
    }

    const domSelection = window.getSelection();
    const domRange = domSelection.getRangeAt(0);
    const rect = domRange.getBoundingClientRect();
    el.style.opacity = "1";
    el.style.top = `${rect.top + window.pageYOffset - el.offsetHeight}px`;
    el.style.left = `${
      rect.left + window.pageXOffset - el.offsetWidth / 2 + rect.width / 2
    }px`;
  });

  return (
    <Portal>
      <Menu
        ref={ref}
        className={css`
          padding: 8px 7px 6px;
          position: absolute;
          z-index: 1;
          top: -10000px;
          left: -10000px;
          margin-top: -6px;
          opacity: 0;
          background-color: #222;
          border-radius: 4px;
          transition: opacity 0.75s;
        `}
      >
        <OperatorButton type="insertLeft" />
        <OperatorButton type="insertRight" />
        <OperatorButton type="insertTop" />
        <OperatorButton type="insertBottom" />
      </Menu>
    </Portal>
  );
};
